package controller

import (
	"mini-app/internal/app/admin/service"
	"mini-app/internal/define"
	"strconv"

	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Goods struct{}

// List 商品列表
func (Goods) List(c *gin.Context) {
	robotID := c.Query("robot_id")
	goodsType, _ := strconv.Atoi(c.Query("goods_type"))
	goodsClass := c.Query("goods_class")
	goodsName := c.Query("goods_name")
	visible, _ := strconv.Atoi(c.Query("visible"))
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	list, total, err := service.Goods{}.List(c.Request.Context(), robotID, goodsType, goodsClass, goodsName, visible, page, limit)
	response.JSON(c, gin.H{
		"list":  list,
		"total": total,
	}, err)
}

// Setting 商品设置
func (Goods) Set(c *gin.Context) {
	var params struct {
		RobotID     string `json:"robot_id"`
		GoodsID     string `json:"goods_id"`
		GoodsName   string `json:"goods_name"`
		PickupType  string `json:"pickup_type"`
		Tag         string `json:"tag"`
		CornerLabel string `json:"corner_label"`
		GoodsClass  string `json:"goods_class"`
		Visible     int    `json:"visible"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, err)
		return
	}
	err = service.Goods{}.Set(
		c.Request.Context(),
		params.RobotID,
		params.GoodsID,
		params.GoodsName,
		params.PickupType,
		params.Tag,
		params.CornerLabel,
		params.GoodsClass,
		params.Visible,
	)
	response.JSON(c, nil, err)
}

func (Goods) SetVisible(c *gin.Context) {
	var params struct {
		GoodsID  string   `json:"goods_id"`
		RobotIDs []string `json:"robot_ids"`
		Visible  int      `json:"visible"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, err)
		return
	}

	if params.Visible == 0 {
		params.Visible = define.State_Yes
	}

	err = service.Goods{}.SetVisible(
		c.Request.Context(),
		params.GoodsID,
		params.RobotIDs,
		params.Visible,
	)
	response.JSON(c, nil, err)
}

// ListGoodsSetting 获取商品设置列表
func (Goods) ListGoodsSetting(c *gin.Context) {
	var params struct {
		GoodsID string `form:"goods_id"`
		Visible int    `form:"visible"`
	}

	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		response.JSON(c, nil, err)
		return
	}
	list, total, err := service.Goods{}.ListGoodsSetting(
		c.Request.Context(),
		params.GoodsID,
		params.Visible,
	)
	response.JSON(c, gin.H{
		"list":  list,
		"total": total,
	}, err)
}
